package com.yuanss.backenddemo.common;

import com.yuanss.backenddemo.entity.po.SysMenu;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.*;

/**
 * @author yuanss
 * @version 1.0
 * @description
 * @date 2024/6/15 22:22:01
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Menu {
    private Long id;
    private String name;
    private Long parentId;
    private String path;
    private List<Menu> children;

    public Menu(Long id, String name, Long parentId) {
        this.id = id;
        this.name = name;
        this.parentId = parentId;
    }

    public static List<Menu> SysMenuToMenuTree(List<SysMenu> menus) {
        List<Menu> menuList = new ArrayList<>();
        for (SysMenu menu : menus) {
            Menu item = Menu.builder()
                    .id(menu.getMenuId())
                    .name(menu.getMenuName())
                    .parentId(menu.getParentId())
                    .path(menu.getPath())
                    .build();
            menuList.add(item);
        }
        return buildMenuTree(menuList);
    }
    // 构建菜单树的方法
    public static List<Menu> buildMenuTree(List<Menu> menus) {
        if (menus == null || menus.isEmpty()) {
            return new ArrayList<>();
        }

        // 创建id到Menu对象的映射
        Map<Long, Menu> idToMenuMap = new HashMap<>();
        for (Menu menu : menus) {
            idToMenuMap.put(menu.getId(), menu);
        }

        List<Menu> rootMenus = new ArrayList<>(); // 存放根节点

        for (Menu menu : menus) {
            if (menu.getParentId() == 0) { // 假设parentId为0的是根节点
                rootMenus.add(menu);
            } else {
                Menu parentMenu = idToMenuMap.get(menu.getParentId());
                if (parentMenu != null) {
                    if(parentMenu.getChildren() == null){
                        parentMenu.setChildren(new ArrayList<>());
                    }
                    parentMenu.getChildren().add(menu);
                }
            }
        }

        return rootMenus;
    }

    // 遍历并打印菜单树的方法
    public void printMenuTree(String prefix) {
        System.out.println(prefix + name);
        for (Menu child : children) {
            child.printMenuTree(prefix + "--");
        }
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        // 创建菜单列表
        List<Menu> menus = Arrays.asList(
                new Menu(1L, "菜单1", 0L), // 根节点
                new Menu(2L, "菜单2", 1L),
                new Menu(3L, "子菜单1", 2L),
                new Menu(4L, "子菜单2", 2L),
                new Menu(5L, "菜单3", 0L), // 另一个根节点
                new Menu(6L, "子菜单3", 5L)
        );

        // 构建菜单树
        List<Menu> menuTree = buildMenuTree(menus);

        // 遍历并打印菜单树
        for (Menu rootMenu : menuTree) {
            rootMenu.printMenuTree("");
        }
    }
}

